<?php

/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: FileController.php 4761 2010-08-21 18:52:33Z huuphuoc $
 * @since		2.0.0
 */
class Upload_FileController extends Zend_Controller_Action {
    /**
     * Watermark font
     * @const string
     */

    const WATERMARK_FONT = 'watermark.ttf';

    public static $fileTypes = array(
        'image' => array('png', 'jpg', 'jpeg', 'bmp', 'gif'),
        'video' => array('flv', 'mp4', 'avi', 'mkv', 'wmv'),
        'audio' => array('mp3', 'wma'),
        'doc' => array('doc', 'docx', 'txt'),
        'ppt' => array('ppt', 'pptx'),
        'xls' => array('xls', 'xlsx'),
        'txt' => array('txt'),
        'psd' => array('psd'),
        'pdf' => array('pdf'),
        'compress' => array('rar', 'zip')
    );

    /* ========== Backend actions =========================================== */

    /**
     * Browse uploaded files
     *
     * @since 2.0.4
     * @return void
     */
    public function browseAction() {
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $path = $request->getParam('path', '');
        $ext = $request->getParam('ext', '');
        $path = ltrim($path, '/');
        $path = rtrim($path, '/');

        $imageSelectCallback = $request->getParam('imageSelectCallback', '');

        /**
         * Breadcump
         */
        $breadcump = '/';

        $fullPath = TOMATO_ROOT_DIR . DS . $path;
        if (!file_exists($fullPath)) {
            $fullPath = TOMATO_ROOT_DIR . DS . 'upload';
            $path = 'upload';
        }

        $breadcump .= $path;

        /**
         * Get config
         */
        $config = Tomato_Module_Config::getConfig('upload');
        $sizes = array();
        foreach ($config->size->toArray() as $key => $value) {
            $sizes[] = $key;
        }

        $dirIterator = new DirectoryIterator($fullPath);
        $dirs = array();
        $files = array();
        foreach ($dirIterator as $file) {
            if ($file->isDot()) {
                continue;
            }
            $name = $file->getFilename();
            if (('CVS' == $name) || ('.svn' == strtolower($name))) {
                continue;
            }
            if ($file->isDir()) {
                $dirs[] = $name;
            } else {
                if (null == $ext) {
                    $files[] = $name;
                } else {
                    $fileExt = substr($name, -3);
                    if (strpos($ext, $fileExt) !== false) {
                        $files[] = $name;
                    }
                }
            }
        }

        $this->view->assign('imageSelectCallback', $imageSelectCallback);
        $this->view->assign('path', $path);
        $this->view->assign('breadcump', explode('/', $breadcump));
        $this->view->assign('prefixUrl', $this->view->APP_STATIC_SERVER . $breadcump);
        $this->view->assign('sizes', $sizes);
        $this->view->assign('dirs', $dirs);
        $this->view->assign('files', $files);
    }

    /**
     * Upload file
     *
     * @return void
     */
    public function uploadAction() {
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();


        $request = $this->getRequest();
        if (!$request->isPost()) {
            return;
        }

        /**
         * Upload file
         */
        $ext = explode('.', $_FILES['Filedata']['name']);
        $extension = $ext[count($ext) - 1];
        //$fileName  = basename($_FILES['Filedata']['name'], '.'.$extension);
        $fileName = uniqid();

        $type = 'orther';
        foreach (self::$fileTypes as $key => $value) {
            if (in_array($extension, $value)) {
                $type = $key;
            }
        }

        /**
         * Prepare folders
         */
        //add public path by trongHM
        $dir = TOMATO_ROOT_DIR . DS . 'public' . DS . 'upload';
        $user = Zend_Auth::getInstance()->getIdentity();
        $userName = $user->username;
        $module = $request->getParam('mod');
        $id = $request->getParam('id');
        /**
         * Prepare insert to database 
         */
        $entity_file = new Multimedia_Models_Entities_File(array(
                    'created_date' => date('Y-m-d H:i:s'),
                    'created_user_id' => $user->id,
                    'created_user_name' => $user->username
                ));
        $fileModel = Rabbit_Model_Factory::getInstance()->setModule('multimedia')->getFileModel();
   
        //switch type
        $ret = array();
        switch ($type) {
            case 'image':
                $entity_file->file_type = 'image';
                /**
                 * Get config
                 */
                $config = Tomato_Module_Config::getConfig('upload');
                $tool = $config->thumbnail->tool;
                $sizes = array();
                foreach ($config->size->toArray() as $key => $value) {
                    list($method, $width, $height) = explode('_', $value);
                    $sizes[$key] = array('method' => $method, 'width' => $width, 'height' => $height);
                }


                $thumbnailSizes = $request->getPost('thumbnails', null);



                $path = implode(DS, array('images', $module, $userName, date('Y'), date('m')));
                Tomato_Utility_File::createDirs($dir, $path);


                $file = $dir . DS . $path . DS . $fileName . '.' . $extension;
                move_uploaded_file($_FILES['Filedata']['tmp_name'], $file);
                $entity_file->url = $file;
                /**
                 * Water mark
                 * @since 2.0.4
                 */
                //		$watermark   = $request->getParam('watermark');
                //		$overlayText = $color = $overlayImage = $position = $sizesApplied = null;
                //
                //		if ($watermark) {
                //			$overlayText  = $request->getParam('text');
                //			$color 		  = $request->getParam('color');
                //			$overlayImage = $request->getParam('image');
                //			$position 	  = $request->getParam('position');
                //			$sizesApplied = $request->getParam('sizes');
                //			$sizesApplied = explode(',', $sizesApplied);
                //		}

                /**
                 * Generate thumbnails if requested
                 */
                if (!isset($thumbnailSizes) || $thumbnailSizes == null) {
                    $thumbnailSizes = array_keys($sizes);
                } else if ($thumbnailSizes != 'none') {
                    $thumbnailSizes = explode(',', $thumbnailSizes);
                }
                $service = null;
                switch (strtolower($tool)) {
                    case 'imagemagick':
                        $service = new Tomato_Image_ImageMagick();
                        break;
                    case 'gd':
                        $service = new Tomato_Image_GD();
                        break;
                }



                /**
                 * Remove script filename from base URL
                 */
                $baseUrl = $this->view->baseUrl();
                if (isset($_SERVER['SCRIPT_NAME']) && ($pos = strripos($baseUrl, basename($_SERVER['SCRIPT_NAME']))) !== false) {
                    $baseUrl = substr($baseUrl, 0, $pos);
                }
                //add public path by TrongHM
                $prefixUrl = rtrim($baseUrl, '/') . '/public/upload/images/' . $module . '/' . $userName . '/' . date('Y') . '/' . date('m');
                $entity_file->image_original = $prefixUrl . '/' . $fileName . '.' . $extension;
                $ret['original'] = array(
                    'url' => $prefixUrl . '/' . $fileName . '.' . $extension,
                    'size' => null,
                );

                if ($thumbnailSizes != 'none') {
                    $service->setFile($file);
                    $ret['original']['size'] = $service->getWidth() . ' x ' . $service->getHeight();

                    foreach ($thumbnailSizes as $s) {
                        $service->setFile($file);
                        $method = $sizes[$s]['method'];
                        $width = $sizes[$s]['width'];
                        $height = $sizes[$s]['height'];

                        $f = $fileName . '_' . $s . '.' . $extension;
                        $newFile = $dir . DS . $path . DS . $f;

                        /**
                         * Create thumbnail
                         */
                        switch ($method) {
                            case 'resize':
                                $service->resizeLimit($newFile, $width, $height);
                                break;
                            case 'crop':
                                $service->crop($newFile, $width, $height);
                                break;
                        }

                        /**
                         * Create watermark if requested
                         */
                        //				if ($watermark) {
                        //					$service->setWatermarkFont(TOMATO_ROOT_DIR . '/data/upload/' . self::WATERMARK_FONT);
                        //					$service->setFile($newFile);
                        //
                        //					if ($overlayText && in_array($s, $sizesApplied)) {
                        //						$service->watermarkText($overlayText, $position, array('color' => $color, 'rotation' => 0, 'opacity' => 50, 'size' => null));
                        //					}
                        //					if ($overlayImage && in_array($s, $sizesApplied)) {
                        //						$overlay = explode('/', $overlayImage);
                        //						$n 		 = count($overlay);
                        //						$overlay = implode(DS, array($dir, 'multimedia', $overlay[$n - 4], $overlay[$n - 3], $overlay[$n - 2], $overlay[$n - 1]));
                        //						$service->watermarkImage($overlay, $position);
                        //					}
                        //
                        
                        $imageField = 'image_' . $s;
                        $entity_file->__set($imageField, $prefixUrl . '/' . $f);
                        $ret[$s] = array(
                            'url' => $prefixUrl . '/' . $f,
                            'size' => $width . ' x ' . $height,
                        );
                        
                        //add to db
                    }
                    $ret['file']['type'] = 'image';
                    $ret['status'] = true;
                }
                if(!$id) $id = $fileModel->add($entity_file);
                $ret['file']['id'] = $id;
                
                break;
            
            default:
                $entity_file->file_type = $type;
                $path = implode(DS, array('files', $module, $userName, date('Y'), date('m')));
                Tomato_Utility_File::createDirs($dir, $path);


                $file = $dir . DS . $path . DS . $fileName . '.' . $extension;

                move_uploaded_file($_FILES['Filedata']['tmp_name'], $file);
                $baseUrl = $this->view->baseUrl();
                if (isset($_SERVER['SCRIPT_NAME']) && ($pos = strripos($baseUrl, basename($_SERVER['SCRIPT_NAME']))) !== false) {
                    $baseUrl = substr($baseUrl, 0, $pos);
                }
                //add public path by TrongHM
                $prefixUrl = rtrim($baseUrl, '/') . '/public/upload/files/' . $module . '/' . $userName . '/' . date('Y') . '/' . date('m');
                $entity_file->url = $prefixUrl . '/' . $fileName . '.' . $extension;
                if(!$id) $id = $fileModel->add($entity_file);

                $ret['status'] = true;
                $ret['file'] = array(
                    'id' => $id,
                    'url' => $prefixUrl . '/' . $fileName . '.' . $extension,
                    'type' => $type,
                    'name' => $fileName . '.' . $extension
                );

                
                break;
        }

        /**
         * Return the reponse
         */
        $ret = Zend_Json::encode($ret);
        $this->getResponse()->setBody($ret);
    }

}